/*
 * Copyright 2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.elves.cloud.controller;

import com.alibaba.fastjson2.JSONObject;
import com.elves.cloud.common.OkHttpUtil;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import org.springframework.format.datetime.standard.DateTimeFormatterFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.security.Principal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * OAuth2 Controller that access the JWT.
 *
 * @author Josh Cummings
 */
@RestController
@Slf4j
public class OAuth2ResourceServerController {

    @GetMapping("/")
    public String index(@AuthenticationPrincipal Jwt jwt) {
        log.info("jwt:{}",jwt.getClaims());
        log.info("jwt:{}",jwt.getTokenValue());
        return String.format("Hello, %s!", jwt.getSubject());
    }

    @GetMapping(value = "/user/{id}")
    @ResponseBody
    public ResponseEntity<Object> userGetID(@PathVariable String id) {
        return new ResponseEntity<>("elves user Welcome 【" + id + "】 at " + LocalDateTime.now().format(new DateTimeFormatterFactory().createDateTimeFormatter()), HttpStatus.OK);
    }

    @GetMapping(value = "/admin/{id}")
    @ResponseBody
    public ResponseEntity<Object> adminGetID(@PathVariable String id) {
        return new ResponseEntity<>("elves admin Welcome 【" + id + "】 at " + LocalDateTime.now().format(new DateTimeFormatterFactory().createDateTimeFormatter()), HttpStatus.OK);
    }

    @GetMapping(value = "/vip/{id}")
    @ResponseBody
    public ResponseEntity<Object> vipGetID(@PathVariable String id) {
        return new ResponseEntity<>("elves vip Welcome 【" + id + "】 at " + LocalDateTime.now().format(new DateTimeFormatterFactory().createDateTimeFormatter()), HttpStatus.OK);
    }
    @GetMapping("/message")
    public String message() {
        return "secret message";
    }

    @GetMapping("/time")
    public String time() {
        return "secret time";
    }

    @ResponseBody
    @GetMapping("/me")
    public String me(Principal principal) {
        log.info("principal:{}", principal);
        return principal.toString();
    }

    @GetMapping(value = "/login/oauth2/code/login-client")
    @ResponseBody
    public ResponseEntity<Object> codeRegectGet(@RequestHeader HttpHeaders headers, @RequestParam String code) {
        log.info("code:{}", code);
        Map<String, List<String>> valueMap = new HashMap<String, List<String>>();
        for (String header : headers.keySet()) {
            valueMap.put(header, headers.get(header));
            log.info("header[{}]={}", header, headers.get(header));
        }
        Map<String, String> map = new HashMap<String, String>();
        map.put("code", code);
        map.put("redirect_uri", "http://app.elves.com:8088/login/oauth2/code/login-client");
        map.put("grant_type", "authorization_code");
        String params = map.toString();
        String response;
        try {
            Response tokenObj = OkHttpUtil.post("http://auth.elves.com:9000/oauth2/token", "login-client", "secret-login", map);
            response = tokenObj.body().string();
            log.info("token obj:{}", response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        JSONObject json = JSONObject.parseObject(response);
        return new ResponseEntity<>(json, HttpStatus.OK);
    }

}
